package com.gaussian.property.app.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.thread.ThreadUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gaussian.property.app.vo.IcsUser;
import com.gaussian.property.module.biz.entity.*;
import com.gaussian.property.module.biz.service.*;
import com.songqi.common.core.constant.Constants;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @description:
 * @author: songqi(13776346982)
 * @date: 2024/4/19 09:24
 */
@Service
public class AppUserService {

    @Resource
    private IAppUserService iAppUserService;

    @Resource
    private IUserProjectService iUserProjectService;
    @Resource
    private IAppUserRoleService iAppUserRoleService;
    @Resource
    private IOptRoleService iOptRoleService;
    @Resource
    private IProjectService iProjectService;

    /**
     *  同步ics系统用户信息
     * @param icsUser
     * @param appUser
     */
    @Transactional(rollbackFor = Exception.class)
    public void synchronizeIcsUser(IcsUser icsUser, AppUser appUser) {
        SynchronizeUserInfoThread thread = new SynchronizeUserInfoThread();
        thread.setIcsUser(icsUser);
        thread.setAppUser(appUser);
        thread.setIAppUserRoleService(iAppUserRoleService);
        thread.setIOptRoleService(iOptRoleService);
        thread.setIProjectService(iProjectService);
        thread.setIUserProjectService(iUserProjectService);
        ThreadUtil.execute(thread);
    }

    public AppUser convert2AppUser(IcsUser icsUser) {
        AppUser appUser;
        Long crewId = icsUser.getCrewId();
        LambdaQueryWrapper<AppUser> queryWrapper = new LambdaQueryWrapper<AppUser>()
                .eq(AppUser::getCrewId, crewId);
        AppUser appUserInDb = iAppUserService.getOne(queryWrapper);
        if (appUserInDb != null) {
            appUser = appUserInDb;
        }else {
            appUser = new AppUser();
            appUser.setCreateTime(LocalDateTime.now());
        }
        appUser.setCrewId(icsUser.getCrewId());
        appUser.setRealName(icsUser.getRealName());
        appUser.setUserName(icsUser.getRealName());
        appUser.setUserType(Constants.YES_CHAR.equals(icsUser.getGaussian()) ? "Admin": "User");
        appUser.setSex(icsUser.getGender());
        appUser.setLastLoginTime(LocalDateTime.now());
        appUser.setUpdateTime(LocalDateTime.now());
        iAppUserService.saveOrUpdate(appUser);
        return appUser;
    }
}
